package utils;

import beans.ListNode;
import beans.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class AlgUtils {


    public static void printBTreeByLevel(TreeNode root){
        if(root == null){
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        int curLevel = 0;
        queue.add(root);
        curLevel ++;
        int nextLevel = 0;
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            if(node.left != null){
                queue.add(node.left);
                nextLevel ++;
            }
            if(node.right != null){
                queue.add(node.right);
                nextLevel ++;
            }
            System.out.print(node.val + " ");
            curLevel --;
            if(curLevel == 0){
                System.out.println();
                curLevel = nextLevel;
                nextLevel = 0;
            }
        }
    }


    public static List<Integer> changeTreeToArrayPreorder(TreeNode root){
        if(root == null){
            return null;
        }
        List<Integer> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            list.add(node.val);
            TreeNode temp = node.left;
            while(temp != null){
                list.add(temp.val);
                queue.add(temp);
                temp = temp.left;
            }
            temp = node.right;
            while(temp != null){
                list.add(temp.val);
                queue.add(temp.right);
                temp = temp.right;
            }
        }
        return list;
    }

    public static ListNode createListNode(int[] arrs){
        if(arrs == null || arrs.length == 0){
            return null;
        }
        ListNode head = new ListNode(arrs[0]);
        ListNode node = head;
        for(int i = 1; i < arrs.length; i ++){
            node.next = new ListNode(arrs[i]);
            node = node.next;
        }
        return head;
    }

    public static void printListNodes(ListNode head){
        while(head != null){
            System.out.print(head.val);
            System.out.print("  ");
            head = head.next;
        }
    }

}


